
package com.ifcar.app.activity.mycomment;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AbsListView.RecyclerListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.ifcar.app.activity.AccountLogin;
import com.ifcar.app.activity.NewsPage;
import com.ifcar.app.activity.WebViewActivity;
import com.ifcar.app.activity.newspage.NewsFragment;
import com.ifcar.app.adapter.CommentAdapter;
import com.ifcar.app.adapter.ReplyMeAdapter;
import com.ifcar.app.fragment.NRLoadingListFrament;
import com.ifcar.app.model.Comment;
import com.ifcar.app.model.MyComment;
import com.ifcar.app.model.ReplyMe;
import com.ifcar.app.rss.GetColumnsInfo;
import com.ifcar.app.rss.GetComments;
import com.ifcar.app.util.ModelUtils;
import com.ifcar.app.util.ShareUtil;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.Tools;
import com.ifcar.app.view.CommentToolsPopup;
import com.ifcar.app.view.FloorsView;
import com.ifcar.app.view.LoadingListView;
import com.ifcar.app.view.FloorsView.FloorViewHolder;
import com.ifcar.app.activity.R;

public class MyCommentFragment extends NRLoadingListFrament implements OnClickListener, OnItemClickListener,
        OnTouchListener, RecyclerListener, MyCommentReply.ActionCallback{
    private String mAccount;

    List<Map<String, Object>> mData;

    private CommentAdapter mAdapter;
    
    private CommentToolsPopup mToolPopup;
    
    private ProgressDialog mProgressDialog;

    private int mToolPopupX;

    private int mToolPopupY;
    
    private float mTextSize;
    
    private MyCommentReply mCommentReply;
    
    private ReplyCommentTask mReplyCommentTask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRefreshTag(getTag());
        Bundle args = getArguments();
        if (args != null) {
            mAccount = args.getString("account");
        }
        setLoadingNum(10);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.mycomment_list_layout, null);
    }

    @Override
    public void onViewCreatedNR(View view, Bundle savedInstanceState) {
        super.onViewCreatedNR(view, savedInstanceState);
        View container = view.findViewById(R.id.reply_edittext_layout);
        mCommentReply = new MyCommentReply(getActivity(), container);
        mCommentReply.setCallback(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAdapter != null) {
            float currentTextSize = NewsFragment.getTextSize(getActivity());
            if (mTextSize != currentTextSize) {
                mTextSize = currentTextSize;
                mAdapter.setTextSize(mTextSize);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        StringUtil.clearRefreshTime(getActivity(), getRefreshTag());
        dismissProgressDialog();
        dismissToolPopup();
    }
    
    private void dismissProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void dismissToolPopup() {
        if (mToolPopup != null && mToolPopup.isShowing()) {
            mToolPopup.dismiss();
        }
    }

    @Override
    public ListAdapter getAdapter() {
        return mAdapter;
    }

    @Override
    public void onLoadingListViewAttached(LoadingListView loadingListView) {
        super.onLoadingListViewAttached(loadingListView);
        loadingListView.getListView().setOnItemClickListener(this);
        loadingListView.getListView().setOnTouchListener(this);
    }

    @Override
    public void onLoadingListViewDetached(LoadingListView loadingListView) {
        super.onLoadingListViewDetached(loadingListView);
        loadingListView.getListView().setOnItemClickListener(null);
        loadingListView.getListView().setOnTouchListener(null);
    }

    @Override
    protected boolean autoRefreshOnFirst() {
        return true;
    }

    @Override
    public boolean isMoreViewShow() {
        return false;
    }
    
    @Override
    public void onTabSelected(boolean first) {
        super.onTabSelected(first);
        if (first) {
            mTextSize = NewsFragment.getTextSize(getActivity());
        }
    }

    @Override
    protected void onRefreshing() {
        super.onRefreshing();
        callLoadingListViewStartLoading(mAdapter == null);

        final Context context = getActivity();
        final int num = getLoadingNum();
        final String account = mAccount;
        final String tag = getTag();

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 取网络
                Map<String, Object> result = null;
                
                if (MyCommentTabFragment.TAB_MY_COMMENT.equals(tag)) {
                    result = MyComment.getMyColumnsByCategory(context, account, 0, num);
                } else {
                    result = ReplyMe.getReplyMe(context, account, 0, num);
                }
                List<Map<String, Object>> list = null;
                if (result != null
                        && !MyComment.FAILED.equals(ModelUtils.getValue(result,
                                MyComment.PARAM_SUCCESS))) {
                    list = (List<Map<String, Object>>) ModelUtils.getValue(result,
                            MyComment.PARAM_LIST);
                }
                if (list == null) {
                    list = new ArrayList<Map<String, Object>>();
                }
                
                if (list != null && list.size() > 0) {
                    StringUtil.updateRefreshTime(context, tag);
                }
                
                Message msg = getHandler().obtainMessage(MSG_REFRESHING);
                msg.obj = list;
                getHandler().sendMessage(msg);
            }
        }).start();
    }

    @Override
    protected void onHandleRefreshing(Object result) {
        super.onHandleRefreshing(result);

        List<Map<String, Object>> data = (List<Map<String, Object>>) result;

        if (data != null && data.size() >= getLoadingNum()) {
            callLoadingListViewAddMoreView();
        }

        if (data != null && data.size() != 0) {
            callLoadingListViewCompleteLoading(true, true);
            setData(data);
        } else {
            Toast.makeText(getActivity(), R.string.msg_loading_failed, Toast.LENGTH_SHORT).show();
            callLoadingListViewCompleteLoading(false, true);
        }
    }

    @Override
    protected void onLoadingMore() {
        super.onLoadingMore();

        final Context context = getActivity();
        final int num = getLoadingNum();
        final String tag = getTag();
        final String account = mAccount;
        final int start = (mData == null || mData.size() == 0) ? 0 : getLoadingStart() + num;
        callLoadingListViewStartLoadingMore(start);
        // 取网络
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, Object> result = null;
                
                if (MyCommentTabFragment.TAB_MY_COMMENT.equals(tag)) {
                    result = MyComment.getMyColumnsByCategory(context, account, start, num);
                } else {
                    result = ReplyMe.getReplyMe(context, account, start, num);
                }

                List<Map<String, Object>> list = null;
                if (result != null
                        && !MyComment.FAILED.equals(ModelUtils.getValue(result,
                                MyComment.PARAM_SUCCESS))) {
                    list = (List<Map<String, Object>>) ModelUtils.getValue(result,
                            MyComment.PARAM_LIST);
                }

                Message msg = getHandler().obtainMessage(MSG_LOADING_MORE);
                msg.obj = list;
                getHandler().sendMessage(msg);
            }
        }).start();
    }

    @Override
    protected void onHandleLoadingMore(Object result) {
        super.onHandleLoadingMore(result);

        List<Map<String, Object>> data = (List<Map<String, Object>>) result;

        if (data == null) {
            // 返回null说明已经网络错误,需要显示加载更多
            Toast.makeText(getActivity(), R.string.msg_loading_failed, Toast.LENGTH_SHORT).show();
            callLoadingListViewCompleteLoadingMore(false, true);
        } else if (data.size() == 0 || data.size() < getLoadingNum()) {
            // 返回数量为0或者小于getLoadingNum(),说明已经加载完,不需要显示加载更多
            callLoadingListViewCompleteLoadingMore(true, false);
            addData(data);
            callLoadingListViewRemoveMoreView();
        } else {
            // 返回数量为0或者小于getLoadingNum(),说明还没加载完,需要显示加载更多
            callLoadingListViewCompleteLoadingMore(true, true);
            addData(data);
        }
    }

    private void setData(List<Map<String, Object>> data) {
        if (data != null && data.size() > 0) {
            mData = data;
            String tag = getTag();

            if (MyCommentTabFragment.TAB_MY_COMMENT.equals(tag)) {
                updateTitle(data.get(0));
                mAdapter = new CommentAdapter(getActivity(), data);
                mAdapter.setTextSize(mTextSize);
            } else {
                mAdapter = new ReplyMeAdapter(getActivity(), data);
                mAdapter.setTextSize(mTextSize);
            }

            ListView listView = getListView();
            if (listView != null) {
                listView.setAdapter(mAdapter);
            }

        }
    }
    
    private void updateTitle(Map<String, Object> first) {
        String fn = (String)ModelUtils.getValue(first, MyComment.PARAM_FQ);
        String name = null;

        if (!TextUtils.isEmpty(fn)) {
            try {
                name = fn.substring(fn.lastIndexOf("[") + 1, fn.lastIndexOf("]"));
            } catch (Exception e) {
                name = null;
            }      
        }
        
        if (TextUtils.isEmpty(name)) {
            if (TextUtils.isEmpty(mAccount)) {
                setTitle(R.string.comment_myself);
            } else {
                setTitle(mAccount);
            }
        } else {
            setTitle(name);
        }
        
        
    }

    private void addData(List<Map<String, Object>> data) {
        if (data == null || data.size() == 0 || mData == null) {
            return;
        }
        mData.addAll(data);
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }
    
    @Override
    public void onMovedToScrapHeap(View view) {
        if (view instanceof FloorsView) {
            FloorsView floors = (FloorsView) view;
            FloorViewHolder holder = floors.getFloorViewHolder();
            if (holder != null) {
                holder.recycleFloorView(floors);
            }
        }
    }
    
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
          if (mCommentReply != null) {
              mCommentReply.finishEdit();
          }
        } else if (action == MotionEvent.ACTION_UP) {
            if (mToolPopup != null && mToolPopup.isHide()) {
                mToolPopup.dismiss();
                return true;
            }
            mToolPopupX = (int) event.getRawX();
            mToolPopupY = (int) event.getRawY();
        }
        return false;
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long itemId) {
        Object tag = adapterView.getItemAtPosition(position);
        if (tag != null) {            
            if (mToolPopup == null) {
                // 初始化工具条弹出框
                mToolPopup = new CommentToolsPopup(getActivity());
                mToolPopup.setContentView(R.layout.mycomment_toolbar);
                mToolPopup.setOnClickListener(this, new int[] {
                        R.id.share_text, R.id.reply_text, R.id.copy_text, R.id.orig_text
                });
            }
            
            // 如果是新闻连接,打开新闻详情页，否则打开webpage
            String url = getOrigUrl((Map<String, Object>) tag);
            if (Comment.validateArticleUrl(url)) {
                mToolPopup.getContentView().findViewById(R.id.orig_text)
                        .setVisibility(View.VISIBLE);
            } else {
                mToolPopup.getContentView().findViewById(R.id.orig_text).setVisibility(View.GONE);
            }
            mToolPopup.setTag(tag);

            int height = (int) (getResources().getDisplayMetrics().density * 55);
            mToolPopup.showAtLocation(adapterView, Gravity.NO_GRAVITY, mToolPopupX, mToolPopupY
                    - height);
        }

    }
    

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (mCommentReply != null && mCommentReply.dispatchKeyEvent(event)) {
            return true;
        }
        
        if (mToolPopup != null && mToolPopup.dispatchKeyEvent(event)) {
            return true;
        }

        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (mToolPopup != null && mToolPopup.isShowing() && dispatchToolPopupClick(id)) {
            return;
        }
    }
    
    private boolean dispatchToolPopupClick(int id) {
        boolean ret = true;
        switch (id) {
            case R.id.share_text: {
                Map<String, Object> data = (Map<String, Object>) mToolPopup.getTag();
                Map<String, Object> map = getFloor(data, getLastFloorNum(data));
                if (map != null) {
                    if (MyCommentTabFragment.TAB_MY_COMMENT.equals(getTag())) {
                        ShareUtil.showShareDialog(getActivity(), getActivity().getTitle()
                                .toString(), map);
                    } else {
                        ShareUtil.showShareDialog(getActivity(), getActivity().getTitle()
                                .toString(), map, getBoardid(data), getS(data));
                    }
                }
                break;
            }
            case R.id.reply_text: {
                Map<String, Object> map = (Map<String, Object>) mToolPopup.getTag();
                if (mCommentReply != null && map != null) {
                    mCommentReply.beginEdit(map);
                }
                break;
            }
            case R.id.copy_text: {
                Map<String, Object> map = (Map<String, Object>) mToolPopup.getTag();
                int last = getLastFloorNum(map);

                StringBuilder sb = new StringBuilder();
                boolean isFault = false;
                for (int i = 1; i <= last; i++) {
                    Map<String, Object> item = getFloor(map, i);
                    if (item == null) {
                        if (!isFault) {
                            isFault = true;
                            
                            if (i > 0) {
                                sb.append("||...");
                            }
                        }
                        
                        continue;
                    }
                    if (i > 1) {
                        sb.append("||");
                    }
                    if (last > 1) {
                        sb.append(i).append("楼:");
                    }
                    sb.append((String) ModelUtils.getValue(item, Comment.PARAM_B));
                }

                Tools.copyText(getActivity(), sb.toString());
                break;
            }
            case R.id.orig_text: {
                Map<String, Object> data = (Map<String, Object>) mToolPopup.getTag();
                // 如果是新闻连接,打开新闻详情页，否则打开webpage
                String url = getOrigUrl(data);
                if (TextUtils.isEmpty(url)) {
                    Toast.makeText(getActivity(), R.string.msg_comment_url_err, Toast.LENGTH_SHORT).show();
                    break;
                }
                if (Comment.validateArticleUrl(url)) {
                    Map<String, Object> map = getFloor(data, getLastFloorNum(data));
                    String docid = (String) ModelUtils.getValue(map, Comment.PARAM_PI);
                    if (!TextUtils.isEmpty(docid)) {
                        String[] ss = docid.split("_");
                        if (ss != null && ss.length > 0) {
                            Bundle b = new Bundle();
                            b.putString(GetColumnsInfo.DOCID_TAG, ss[0]);
                            b.putBoolean("isCollect", true);
                            b.putBoolean("iscomeMyReply", true);
                            b.putString("position", "0"); // 当前位置
                            b.putString(GetColumnsInfo.TID_TAG, "attitude"); // 类型
                                                                             // 另一面
                                                                             // 态度
                            b.putString(GetColumnsInfo.URL_TAG, url);
                            Intent intent = new Intent(getActivity(), NewsPage.class);
                            intent.putExtras(b);
                            startActivity(intent);
                        }
                    }
                } else {
                    Intent intent = new Intent(getActivity(), WebViewActivity.class);
                    intent.putExtra("url", url);
                    intent.putExtra("title", getS(data));
                    startActivity(intent);
                }

                break;
            }
            default:
                ret = false;
                break;
        }
        if (ret) {
            mToolPopup.dismiss();
        }
        return ret;
    }
    
    
    /**
     * 获取最后楼层标识
     * 
     * @param map
     * @return
     */
    private int getLastFloorNum(Map<String, Object> map) {
        if (map == null || mAdapter == null) {
            return -1;
        }
        int last = mAdapter.getLastFloorNum(map);
        if (last <= 0) {
            return -1;
        }
        return last;
    }

    /**
     * 获取跟帖中某一楼层的数据
     * 
     * @param map
     * @param num
     * @return
     */
    private Map<String, Object> getFloor(Map<String, Object> map, int num) {
        if (map == null || mAdapter == null) {
            return null;
        }
        return mAdapter.getFloor(map, num);
    }
    
    /**
     * 得到原文连接
     * @param data
     * @return
     */
    private String getOrigUrl(Map<String, Object> data) {
        if (MyCommentTabFragment.TAB_MY_COMMENT.equals(getTag())) {
            Map<String, Object> map = (Map<String, Object>) getFloor(data, getLastFloorNum(data));
            return (String) ModelUtils.getValue(map, Comment.PARAM_K);
        }

        return (String) ModelUtils.getValue(data, Comment.PARAM_K);
    }
    
    /**
     * 得到文章id
     * @param data
     * @return
     */
    private String getDocId(Map<String, Object> data) {
        Map<String, Object> map = getFloor(data, getLastFloorNum(data));
        final String pi = (String) ModelUtils.getValue(map, Comment.PARAM_PI);
        String tmpDocid = null;
        if (!TextUtils.isEmpty(pi)) {
            String[] ss = pi.split("_");
            if (ss != null && ss.length > 0) {
                tmpDocid = ss[0];
            }
        }
        return tmpDocid;
    }
    
    /**
     * 得到版面id
     * @param data
     * @return
     */
    private String getBoardid(Map<String, Object> data) {
        if (MyCommentTabFragment.TAB_MY_COMMENT.equals(getTag())) {
            Map<String, Object> map = (Map<String, Object>) getFloor(data, getLastFloorNum(data));
            return (String) ModelUtils.getValue(map, Comment.PARAM_BI);
        }

        return (String) ModelUtils.getValue(data, Comment.PARAM_BI);
    }
    
    /**
     * 得到文章名称
     * @param data
     * @return
     */
    private String getS(Map<String, Object> data) {
        if (MyCommentTabFragment.TAB_MY_COMMENT.equals(getTag())) {
            Map<String, Object> map = (Map<String, Object>) getFloor(data, getLastFloorNum(data));
            return (String) ModelUtils.getValue(map, Comment.PARAM_S);
        }

        return (String) ModelUtils.getValue(data, Comment.PARAM_S);
    }
    
    @Override
    public void onReplyAction(MyCommentReply commonReply, int action) {
        switch (action) {
            case MyCommentReply.ACTION_REPLY: {
                String content = commonReply.getReplyContent();
                boolean replyWithQuote = false;
                String quote = null;

                Map<String, Object> data = (Map<String, Object>) commonReply.getEditTag();
                if (data != null) {
                    String docid = getDocId(data);
                    if (TextUtils.isEmpty(docid)) {
                        return;
                    }
                    
                    String boardid = getBoardid(data);
                    if (TextUtils.isEmpty(boardid)) {
                        return;
                    }
                   
                    Map<String, Object> lastFloor = getFloor(data, getLastFloorNum(data));
                    String p = (String) ModelUtils.getValue(lastFloor, Comment.PARAM_P);
                    if (!TextUtils.isEmpty(p)) {
                        replyWithQuote = true;
                        if (p.contains(docid)) {
                            quote = p;
                        } else {
                            quote = docid + "_" + p;
                        }
                    }
                    
                    replyComment(content, boardid, docid, replyWithQuote, quote);
                }
                break;
            }

            default:
                break;
        }
        
    }
    
    private void replyComment(String content, String bi, String docId, boolean replyWithQuote, String quote) {
        Context context = getActivity();

        if (TextUtils.isEmpty(content)) {
            Toast.makeText(context, "不能发空消息", Toast.LENGTH_SHORT).show();
            return;
        } else if (content.length() <= 1 || content.length() > 1000) {
            Toast.makeText(context, "回复请在2-1000字内", Toast.LENGTH_SHORT).show();
            return;
        }

        SharedPreferences set_prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String account = set_prefs.getString("account", "");

        if (TextUtils.isEmpty(account)) {
            Intent Loginintent = new Intent(context, AccountLogin.class);
            Loginintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Bundle bundle = new Bundle();

            bundle.putBoolean("isreply", true);
            bundle.putBoolean("replyWithQuote", replyWithQuote);

            bundle.putString("replydocid", docId);
            bundle.putString("replyquote", quote);
            bundle.putString("replyBoard", bi);
            bundle.putString("replycontent", content);
            Loginintent.putExtras(bundle);
            context.startActivity(Loginintent);
        } else {
            ReplyCommentTaskParam p = new ReplyCommentTaskParam();
            p.boardid = bi;
            p.docid = docId;
            p.quote = quote;
            p.content = content;
            p.account = account;
            p.replyWithQuote = replyWithQuote;
            p.context = getActivity();
            cancelReplyCommentTask();

            if (mProgressDialog == null) {
                mProgressDialog = new ProgressDialog(getActivity());
                mProgressDialog.setMessage("正在发表跟贴...");
                mProgressDialog.setCancelable(true);

                mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        cancelReplyCommentTask();
                    }
                });
            }
            mProgressDialog.show();
            mReplyCommentTask = new ReplyCommentTask();
            mReplyCommentTask.execute(p);

        }
    }
    
    private void cancelReplyCommentTask() {
        if (mReplyCommentTask != null && !mReplyCommentTask.isCancelled()) {
            mReplyCommentTask.cancel(true);
            mReplyCommentTask = null;
        }
        if (mCommentReply != null) {
            mCommentReply.finishEdit();
        }
        dismissProgressDialog();
    }

    
    @Override
    public void onApplyTheme() {
        super.onApplyTheme();
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
        if (mCommentReply != null) {
            mCommentReply.onApplyTheme(getActivity(), getThemeSettingsHelper());
        }
    }
    
    /**
     * 回复跟帖任务
     * 
     * @author wjying
     */
    private class ReplyCommentTask extends AsyncTask<ReplyCommentTaskParam, Object, Object> {

        @Override
        protected Object doInBackground(ReplyCommentTaskParam... params) {
            if (params == null || params.length == 0 || params[0] == null) {
                return null;
            }

            

            ReplyCommentTaskParam p = params[0];
            String boardid = p.boardid;
            String docid = p.docid;
            String account = p.account;
            String content = p.content;
            boolean replyWithQuote = p.replyWithQuote;
            String quote = p.quote;
            Context context = p.context;
            
            String result;
            if (replyWithQuote) {
                result = GetComments.postComment(boardid, docid, quote, content, account,
                        "新闻客户端用户", "0.0.0.0", "false", context);
            } else {
                result = GetComments.postComment(boardid, docid, content, account, "新闻客户端用户",
                        "0.0.0.0", "false", context);
            }

            return result;
        }

        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);
            dismissProgressDialog();
            if (isCancelled() || result == null || !isAdded()) {
                return;
            }

            String ret = (String) result;
            if ("1".equals(ret)) {
                Toast.makeText(getActivity(), "发表成功", Toast.LENGTH_SHORT).show();
            } else if (TextUtils.isEmpty(ret)) {
                Toast.makeText(getActivity(), "发表失败", Toast.LENGTH_SHORT).show();
            } else {
                ret = ret.toLowerCase();

                if (ret.contains("postdata")) {
                    ret = "内容含有非法字符";
                }

                Toast.makeText(getActivity(), "发表失败" /*，原因:" + ret*/, Toast.LENGTH_SHORT).show();
            }
        }
    }

    private class ReplyCommentTaskParam {
        String boardid;

        String docid;

        String account;

        String content;

        boolean replyWithQuote;

        String quote;

        int type;
        
        Context context;
    }

}
